package com.njxzc.service.before;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njxzc.common.http.ResponseResult;
import com.njxzc.common.security.anno.AuthIgrone;
import com.njxzc.common.security.utiles.ConfigrarionBean;
import com.njxzc.common.security.utiles.JwtTokenUtil;
import com.njxzc.common.security.utiles.MD5Util;
import com.njxzc.common.security.utiles.RedisUtil;
import com.njxzc.entity.BUserEntity;
import com.njxzc.mapper.before.BUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class BUserServiceImpl extends ServiceImpl<BUserMapper,BUserEntity> implements BUserService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private ConfigrarionBean config;

    @Override
    public ResponseResult<Map<String, Object>> register(BUserEntity bUserEntity) {
        bUserEntity.setBpwd(MD5Util.MD5(bUserEntity.getBpwd()));
        Long count = lambdaQuery().eq(BUserEntity::getBemail, bUserEntity.getBemail()).count();
        if(count>0) {
        return ResponseResult.getMessageResult(null,"A001");
        }else if(save(bUserEntity)){
            return ResponseResult.getMessageResult(null,"A002");
        }else{
            return ResponseResult.getMessageResult(null,"A003");
        }
    }

    @Override
    public ResponseResult<Map<String, String>> login(BUserEntity bUserEntity) {
        String code = (String)redisUtil.get("code");
        if(!code.equalsIgnoreCase(bUserEntity.getCode())){
            return ResponseResult.getMessageResult(null,"A004");
        }
        Long count = lambdaQuery().eq(BUserEntity::getBemail, bUserEntity.getBemail()).count();
        if(count==0){
            return ResponseResult.getMessageResult(null,"A001");
        }
        //bUserEntity.setBemail(MD5Util.MD5(bUserEntity.getBemail()));
        List<BUserEntity> list = lambdaQuery()
                .eq(BUserEntity::getBemail, bUserEntity.getBemail())
                .eq(BUserEntity::getBpwd, MD5Util.MD5(bUserEntity.getBpwd())).list();
        if(!list.isEmpty()){
            String token = jwtTokenUtil.createToken(bUserEntity.getBemail());
            redisUtil.set("login_"+bUserEntity.getBemail(),bUserEntity.getBemail(), config.getExpiration());
            HashMap<String,String> myRes= new HashMap<>();
            myRes.put("buserauthtoken",token);
            myRes.put("bemail",bUserEntity.getBemail());
            myRes.put("bid",list.get(0)+"");
            return ResponseResult.getSuccessResult(myRes);
        }else{
            return ResponseResult.getMessageResult(null,"A002");
        }
    }
}
